package org.springblade.modules.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.exception.TrainingServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.NumberUtil;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.modules.api.vo.ApiJxcStatisticsVo;
import org.springblade.modules.classes.entity.ClassesEntity;
import org.springblade.modules.classes.entity.ClassesPlanEntity;
import org.springblade.modules.classes.entity.ClassesUserEntity;
import org.springblade.modules.classes.entity.TrainingPlanEntity;
import org.springblade.modules.classes.service.IClassesPlanService;
import org.springblade.modules.classes.service.IClassesService;
import org.springblade.modules.classes.service.IClassesUserService;
import org.springblade.modules.classes.service.ITrainingPlanService;
import org.springblade.modules.classes.vo.ClassesVO;
import org.springblade.modules.classes.vo.TrainingPlanVO;
import org.springblade.modules.classes.wrapper.ClassesPlanWrapper;
import org.springblade.modules.classes.wrapper.ClassesWrapper;
import org.springblade.modules.classes.wrapper.TrainingPlanWrapper;
import org.springblade.modules.item.entity.ItemEntity;
import org.springblade.modules.item.service.IItemService;
import org.springblade.modules.library.entity.QuestionBankEntity;
import org.springblade.modules.library.service.IQuestionBankService;
import org.springblade.modules.log.entity.IntegralLogEntity;
import org.springblade.modules.log.service.IIntegralLogService;
import org.springblade.modules.material.entity.PaperAnswerEntity;
import org.springblade.modules.material.service.IAnswerService;
import org.springblade.modules.material.vo.PaperAnswerVO;
import org.springblade.modules.material.wrapper.AnswerWrapper;
import org.springblade.modules.personal.entity.UserBaseEntity;
import org.springblade.modules.personal.service.IUserBaseService;
import org.springblade.modules.personal.vo.UserBaseVO;
import org.springblade.modules.resource.entity.Attach;
import org.springblade.modules.resource.enums.AttachType;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springblade.modules.teaching.entity.CourseChapterSubFileEntity;
import org.springblade.modules.teaching.service.ICourseChapterSubFileService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDateTime;
import java.time.Year;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RestController
@AllArgsConstructor
@RequestMapping("jxc-external")
@Api(value = "开放给jxc的数据接口", tags = "对外的数据接口")
public class JxcExternalController {

	private final IClassesService classesService;
	private final IClassesUserService classesUserService;
	private final IClassesPlanService classesPlanService;
	private final IAnswerService answerService;
	private final IUserService userService;
	private final IRoleService roleService;
	private final ITrainingPlanService trainingPlanService;
	private final IUserBaseService userBaseService;
	private final IIntegralLogService integralLogService;
	private final ICourseChapterSubFileService courseChapterSubFileService;
	private final IQuestionBankService questionBankService;
	private final IItemService itemService;

	public static final String YEAR_START_TIME = "startTime";
	public static final String YEAR_END_TIME = "endTime";

	/**
	 * 学员成绩分页接口
	 */
	@GetMapping("/score-list")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "学员成绩分页接口", notes = "可传参：用户姓名-realName")
	public R scoreList(String userName, Query query) {
		LambdaQueryWrapper<PaperAnswerEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		if (StringUtils.isNotBlank(userName)) {
			List<UserBaseEntity> userList = userBaseService.listByUserName(userName);

			if (CollectionUtil.isNotEmpty(userList)) {
				lambdaQueryWrapper.in(PaperAnswerEntity::getUserId, userList.stream().map(UserBaseEntity::getUserId).collect(Collectors.toList()));
			}
		}
		IPage<PaperAnswerEntity> pages = answerService.page(Condition.getPage(query), lambdaQueryWrapper);

		IPage<PaperAnswerVO> paperAnswerVOIPage = AnswerWrapper.build().pageVO(pages);
		paperAnswerVOIPage.getRecords().forEach(pageVO -> {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserId(pageVO.getUserId());
			if (null != userBaseEntity && null != userBaseEntity.getUserName())
				pageVO.setRealName(userBaseEntity.getUserName());

		});
		return R.data(paperAnswerVOIPage);
	}


	/**
	 * 培训计划表 分页
	 */
	@GetMapping("/training-plan-list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "培训计划接口", notes = "可传参：培训计划名称-planName,年度(YYYY)-year")
	public R list(String planName,String year, Query query) {
		LambdaQueryWrapper<TrainingPlanEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(planName))
			lambdaQueryWrapper.like(TrainingPlanEntity::getPlanName, planName);
		if (StringUtils.isNotBlank(year))
			lambdaQueryWrapper.eq(TrainingPlanEntity::getYear, year);

		lambdaQueryWrapper.orderByDesc(TrainingPlanEntity::getCreateTime);
		IPage<TrainingPlanEntity> pages = trainingPlanService.page(Condition.getPage(query), lambdaQueryWrapper);
		IPage<TrainingPlanVO> trainingPlanVOIPage = TrainingPlanWrapper.build().pageVO(pages);
		//设置培训计划的相关课程
//		List<Long> trainPlanIds=trainingPlanVOIPage.getRecords().stream().map(TrainingPlanVO::getId).collect(Collectors.toList());
//		trainingPlanVOIPage.setRecords(trainingPlanService.trainingPlanDetail(trainPlanIds,trainingPlanVOIPage.getRecords()));
		return R.data(trainingPlanVOIPage);
	}


	/**
	 * 班级分页列表
	 */
	@GetMapping("/classes-list")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "班级分页列表", notes = "可传参：班级名称-classesName")
	public R<IPage<ClassesVO>> classesList(String classesName, Query query) {
		LambdaQueryWrapper<ClassesEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(classesName))
			lambdaQueryWrapper.like(ClassesEntity::getClassesName, classesName);
		IPage<ClassesEntity> pages = classesService.page(Condition.getPage(query), lambdaQueryWrapper);

		IPage<ClassesVO> classesVOIPage = ClassesWrapper.build().pageVO(pages);
		classesVOIPage.getRecords().forEach(vopage -> {
			//班级人员明细
			long classesUserConut = 0;
			List<ClassesUserEntity> classesUserEntityList = classesUserService.list(Wrappers.<ClassesUserEntity>query().lambda()
				.eq(ClassesUserEntity::getClassesId, vopage.getId()));
			if (CollectionUtil.isNotEmpty(classesUserEntityList)) {
				classesUserConut = classesUserEntityList.size();

				vopage.setClassesUserList(userBaseService.list(Wrappers.<UserBaseEntity>query().lambda()
					.in(UserBaseEntity::getUserId, classesUserEntityList.stream().map(ClassesUserEntity::getUserId).collect(Collectors.toList()))));
			}

			//班级总人数
			vopage.setStudents(classesUserConut);

			//班级的培训计划
			ClassesPlanEntity classesPlanEntity = classesPlanService.getOne(Wrappers.<ClassesPlanEntity>query().lambda()
				.eq(ClassesPlanEntity::getClassesId, vopage.getId()));
			if (null != classesPlanEntity) {
				TrainingPlanEntity trainingPlanEntity = trainingPlanService.getById(classesPlanEntity.getPlanId());
				if (null != trainingPlanEntity) {
					vopage.setTrainingPlanName(trainingPlanEntity.getPlanName());
					vopage.setClassesPlan(ClassesPlanWrapper.build().entityVO(classesPlanEntity));
					vopage.setTrainPlanId(trainingPlanEntity.getId());
				}
			}
		});
		return R.data(classesVOIPage);
	}


	/**
	 * 个人受训记录的接口
	 */
	@GetMapping("/myself-participate-list")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "个人受训记录的接口", notes = "可传参：培训计划名称-planName,年度(YYYY)-year")
	public R myselfParticipateTrainingPlanlist(String userName,String year, Query query) {
		if (StringUtils.isBlank(userName)) throw new TrainingServiceException("请输入用户姓名");
		UserBaseEntity userBaseEntity = userBaseService.selectByUserName(userName);
		if (null == userBaseEntity) throw new TrainingServiceException("没有找到名字为:" + userName + "的用户");

		Long userId = userBaseEntity.getUserId();
		//该用户参与过的培训计划ids
		List<Long> trainPlanIds = trainingPlanService.getUserTrainingPlanIds(userId);
		if (null == trainPlanIds) return R.success("暂无数据");

		LambdaQueryWrapper<TrainingPlanEntity> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(TrainingPlanEntity::getId, trainPlanIds);
		if (StringUtils.isNotBlank(year))
			queryWrapper.eq(TrainingPlanEntity::getYear, year);

		IPage<TrainingPlanEntity> pages = trainingPlanService.page(Condition.getPage(query), queryWrapper);
		IPage<TrainingPlanVO> trainingPlanVOIPage = TrainingPlanWrapper.build().pageVO(pages);
		trainingPlanVOIPage.setRecords(trainingPlanService.trainingPlanDetail(trainPlanIds, trainingPlanVOIPage.getRecords()));//给每条培训计划赋予对应的课程详情
		return R.data(trainingPlanVOIPage);
	}

	/**
	 * 教师列表接口
	 */
	@GetMapping("/teacher-list")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "教师列表接口", notes = "可传参：内训专业类别-trainingMajorCategory,内训专业方向-trainingMajorDirection,聘任等级-appointmentGrade")
	public R teacherList(String trainingMajorCategory,String trainingMajorDirection,String appointmentGrade, Query query) {
		List<Long> roleIds = roleService.getRoleIdsByLikeRoleName("师");
		if (CollectionUtil.isEmpty(roleIds)) return R.success("没有配置老师");

		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		for (Long roleId : roleIds) {
			lambdaQueryWrapper.or().like(User::getRoleId, roleId);
		}
		List<User> userList = userService.list(lambdaQueryWrapper);
		if (CollectionUtil.isEmpty(userList)) return R.success("没有配置老师");

		//获取教师的userIds
		List<Long> userIds = userList.stream().map(User::getId).collect(Collectors.toList());
		LambdaQueryWrapper<UserBaseEntity> userBaseWrapper = new LambdaQueryWrapper<>();
		userBaseWrapper.in(UserBaseEntity::getUserId, userIds);

		if (StringUtils.isNotBlank(trainingMajorCategory))
			userBaseWrapper.like(UserBaseEntity::getTrainingMajorCategory, trainingMajorCategory);
		if (StringUtils.isNotBlank(trainingMajorDirection))
			userBaseWrapper.like(UserBaseEntity::getTrainingMajorDirection,trainingMajorDirection);
		if (StringUtils.isNotBlank(appointmentGrade))
			userBaseWrapper.like(UserBaseEntity::getAppointmentGrade, appointmentGrade);

		return R.data(userBaseService.page(Condition.getPage(query), userBaseWrapper));
	}


	/**
	 * 学员当年度获取积分记录的接口
	 */
	@GetMapping("/integral-list")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "学员当年度获取积分记录的接口", notes = "可传参：用户姓名-userName,年度-year,得分渠道-integralOrigin,得分项目-projectOrigin")
	public R integralList(String userName,String year,String integralOrigin,String projectOrigin, Query query) {
		LambdaQueryWrapper<IntegralLogEntity> logEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();

		if (StringUtils.isNotBlank(userName)) {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserName(userName);
			if (null == userBaseEntity) throw new TrainingServiceException("没有找到名字为:" +userName + "的用户");
			logEntityLambdaQueryWrapper.eq(IntegralLogEntity::getUserId, userBaseEntity.getUserId());
		}

		if (null !=year) logEntityLambdaQueryWrapper.like(IntegralLogEntity::getYear,year);
		if (null !=integralOrigin)
			logEntityLambdaQueryWrapper.like(IntegralLogEntity::getIntegralOrigin, integralOrigin);
		if (null != projectOrigin)
			logEntityLambdaQueryWrapper.like(IntegralLogEntity::getProjectOrigin, projectOrigin);

		return R.data(integralLogService.page(Condition.getPage(query), logEntityLambdaQueryWrapper));
	}

	/**
	 * 统计数据接口-教师
	 * 不同级别的教师数量 及明细
	 */
	@GetMapping("/statistics-teacher")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "统计数据接口-教师", notes = "")
	public R statisticsTeacher() {
		List<ApiJxcStatisticsVo> resultList = new ArrayList<>();

		List<Long> roleIds = roleService.getRoleIdsByLikeRoleName("师");
		if (CollectionUtil.isEmpty(roleIds)) return R.success("没有配置老师");

		LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		for (Long roleId : roleIds) {
			lambdaQueryWrapper.or().like(User::getRoleId, roleId);
		}
		List<User> userList = userService.list(lambdaQueryWrapper);
		if (CollectionUtil.isEmpty(userList)) return R.success("没有配置老师");

		//获取教师的userIds
		List<Long> userIds = userList.stream().map(User::getId).collect(Collectors.toList());
		LambdaQueryWrapper<UserBaseEntity> userBaseWrapper = new LambdaQueryWrapper<>();
		userBaseWrapper.in(UserBaseEntity::getUserId, userIds);

		//查询出教师总量
		List<UserBaseEntity> totalList = userBaseService.list(userBaseWrapper);
		if (CollectionUtil.isEmpty(totalList)) return R.success("没有配置老师");

		ApiJxcStatisticsVo total = new ApiJxcStatisticsVo();
		total.setName("教师");
		total.setNumber((long) totalList.size());
		total.setDetailList(totalList);

		//教师等级分组
		List<String> appointmentGradeList = totalList.stream().map(UserBaseEntity::getAppointmentGrade).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
		appointmentGradeList.forEach(appointmentGrade -> {
			ApiJxcStatisticsVo vo = new ApiJxcStatisticsVo();
			List<UserBaseEntity> list = userBaseService.list(Wrappers.<UserBaseEntity>query().lambda().in(UserBaseEntity::getUserId, userIds).eq(UserBaseEntity::getAppointmentGrade, appointmentGrade));
			vo.setName(appointmentGrade);
			vo.setNumber((long) list.size());
			vo.setDetailList(list);

			resultList.add(vo);
		});
		return R.data(resultList);

	}


	/**
	 * 统计数据接口-课件量
	 * 及明细
	 */
	@GetMapping("/statistics-courseware")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "统计数据接口-课件", notes = "可传参：年度-year")
	public R statisticsCourseware(String year) {
		List<ApiJxcStatisticsVo> resultList = new ArrayList<>();

		ApiJxcStatisticsVo total = new ApiJxcStatisticsVo();
		LambdaQueryWrapper<CourseChapterSubFileEntity> totalWrapper = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<CourseChapterSubFileEntity> vedioWrapper = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<CourseChapterSubFileEntity> coursewareWrapper = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(year)) {
			Map<String, LocalDateTime> yearTimeMap = currentYearConvert(year);
			if (null!=yearTimeMap) {
				totalWrapper.ge(CourseChapterSubFileEntity::getCreateTime, yearTimeMap.get(YEAR_START_TIME));
				totalWrapper.le(CourseChapterSubFileEntity::getCreateTime, yearTimeMap.get(YEAR_END_TIME));

				vedioWrapper.ge(CourseChapterSubFileEntity::getCreateTime,  yearTimeMap.get(YEAR_START_TIME));
				vedioWrapper.le(CourseChapterSubFileEntity::getCreateTime,  yearTimeMap.get(YEAR_END_TIME));

				coursewareWrapper.ge(CourseChapterSubFileEntity::getCreateTime,  yearTimeMap.get(YEAR_START_TIME));
				coursewareWrapper.le(CourseChapterSubFileEntity::getCreateTime,  yearTimeMap.get(YEAR_END_TIME));
			}
		}

		List<CourseChapterSubFileEntity> totalList = courseChapterSubFileService.list(totalWrapper);
		total.setName("课件");
		total.setNumber((long) totalList.size());
		total.setDetailList(totalList);
		resultList.add(total);

		ApiJxcStatisticsVo vedio = new ApiJxcStatisticsVo();
		vedioWrapper.eq(CourseChapterSubFileEntity::getAttachType, AttachType.COURSE_VEDIO.getCategory());
		List<CourseChapterSubFileEntity> vedioList = courseChapterSubFileService.list(vedioWrapper);
		vedio.setName("学习视频");
		vedio.setNumber((long) vedioList.size());
		vedio.setDetailList(vedioList);
		resultList.add(vedio);


		ApiJxcStatisticsVo courseware = new ApiJxcStatisticsVo();
		coursewareWrapper.eq(CourseChapterSubFileEntity::getAttachType, AttachType.COURSE_COURSEWARE.getCategory());
		List<CourseChapterSubFileEntity> coursewareList = courseChapterSubFileService.list(coursewareWrapper);
		courseware.setName("学习课件");
		courseware.setNumber((long) coursewareList.size());
		courseware.setDetailList(coursewareList);
		resultList.add(courseware);

		return R.data(resultList);
	}


	/**
	 * 统计数据接口-题库量及明细
	 * 年度下的各题目性质的数量
	 */
	@GetMapping("/statistics-question-bank")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "统计数据接口-题库量", notes = "可传参：年度-year,")
	public R statisticsQuestionBank(String year) {
		if (StringUtils.isBlank(year)) throw new TrainingServiceException("请输入年度");

		LambdaQueryWrapper<QuestionBankEntity> totalWrapper = new LambdaQueryWrapper<>();
		if (StringUtils.isNotBlank(year)) {
			Map<String, LocalDateTime> yearTimeMap = currentYearConvert(year);
			if (null!=yearTimeMap) {
				totalWrapper.ge(QuestionBankEntity::getCreateTime, yearTimeMap.get(YEAR_START_TIME));
				totalWrapper.le(QuestionBankEntity::getCreateTime, yearTimeMap.get(YEAR_END_TIME));
			}
		}
		//该年度的总数里
		long totalCount = questionBankService.count(totalWrapper);
		ApiJxcStatisticsVo vo=new ApiJxcStatisticsVo();
		vo.setName("年度:"+year);
		vo.setNumber(totalCount);

		totalWrapper.groupBy(QuestionBankEntity::getQuestionProperties);
		List<String> questuonPropertiesList = questionBankService.list(totalWrapper).stream().map(QuestionBankEntity::getQuestionProperties).collect(Collectors.toList());



		List<ApiJxcStatisticsVo> questuonPropertiesDetailList=new ArrayList<>();


		questuonPropertiesList.forEach(questuonProperties->{
			LambdaQueryWrapper<QuestionBankEntity> questionPropertiesWrapper = new LambdaQueryWrapper<>();
			if (StringUtils.isNotBlank(year)) {
				Map<String, LocalDateTime> yearTimeMap = currentYearConvert(year);
				if (null!=yearTimeMap) {
					questionPropertiesWrapper.ge(QuestionBankEntity::getCreateTime, yearTimeMap.get(YEAR_START_TIME));
					questionPropertiesWrapper.le(QuestionBankEntity::getCreateTime, yearTimeMap.get(YEAR_END_TIME));
				}
			}
			questionPropertiesWrapper.eq(QuestionBankEntity::getQuestionProperties,questuonProperties);
			List<QuestionBankEntity> questuonPropertiesQuestion = questionBankService.list(questionPropertiesWrapper);
			ApiJxcStatisticsVo apiJxcStatisticsVo=new ApiJxcStatisticsVo();
			apiJxcStatisticsVo.setName(questuonProperties);
			apiJxcStatisticsVo.setNumber((long) questuonPropertiesQuestion.size());
			apiJxcStatisticsVo.setDetailList(questuonPropertiesQuestion);
			questuonPropertiesDetailList.add(apiJxcStatisticsVo);
		});
		vo.setDetailList(questuonPropertiesDetailList);
		return R.data(vo);
	}


	/**
	 * 统计数据接口-教具
	 * 及明细
	 */
	@GetMapping("/statistics-item")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "统计数据接口-教具", notes = "")
	public R statisticsItem() {
		LambdaQueryWrapper<ItemEntity> totalWrapper = new LambdaQueryWrapper<>();

		List<ItemEntity> itemEntityList = itemService.list(totalWrapper);
		ApiJxcStatisticsVo apiJxcStatisticsVo=new ApiJxcStatisticsVo();
		apiJxcStatisticsVo.setName("教具");
		apiJxcStatisticsVo.setNumber((long) itemEntityList.size());
		apiJxcStatisticsVo.setDetailList(itemEntityList);
		return R.data(apiJxcStatisticsVo);
	}

	/**
	 * 传入年度YYYY
	 */
	public static Map<String, LocalDateTime> currentYearConvert(String year) {
		Map<String, LocalDateTime> map=new HashMap<>();
		int numberYear = NumberUtil.toInt(year);
		LocalDateTime startTime= LocalDateTime.of(numberYear, 1, 1, 0, 0, 0);
		LocalDateTime endTime= LocalDateTime.of(numberYear, 12, 31, 23, 59, 59);
		map.put(YEAR_START_TIME,startTime);
		map.put(YEAR_END_TIME,endTime);
		return map;
	}




}
